import { APIResult } from '@/requestErrorConfig';
import { Form } from 'antd';
import { useEffect, useState } from 'react';
import message from './message';

export default ({
  editApi,
  addApi,
  successCb,
}: {
  editApi?: (data: any) => Promise<APIResult<any>>;
  addApi?: (data: any) => Promise<APIResult<any>>;
  successCb?: () => void;
}) => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [currentData, setCurrentData] = useState<any>(null);

  useEffect(() => {
    if (currentData) {
      form.setFieldsValue(currentData);
    } else {
      form.resetFields();
    }
  }, [currentData]);

  const onCancel = () => {
    setCurrentData(null);
  };

  const onSave = async (v: any, id?: any) => {
    const fetchApi = v.id !== undefined || id !== undefined ? editApi : addApi;
    if (fetchApi) {
      setLoading(true);
      const { rsCode } = await fetchApi(v);
      setLoading(false);
      if (rsCode === '00000000') {
        message.success('保存成功');
        onCancel();
        if (successCb) successCb();
      }
    }
  };

  const onOk = async () => {
    form
      .validateFields()
      .then((v: any) => {
        onSave(v);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  return {
    loading,
    form,
    currentData,
    setCurrentData,
    setLoading,
    onOk,
    onCancel,
    onSave,
  };
};
